package util;

import java.util.ArrayList;


class ListNode {
    int val;
    ListNode next;
    ListNode() { }
    ListNode(int val) {this.val = val;}
    ListNode(int val, ListNode next) {}
}

public class nodeAndArray {

    //链表转数组
    public static void nodeTolist(ListNode node){
        ArrayList<Integer> list = new ArrayList<>();
        while(node != null){
            list.add(node.val);
            node = node.next;
        }
        System.out.println();
        System.out.println(list);
    }

    //数组转链表
    public static  ListNode arrayToNode(int[] arr){
        ListNode head = new ListNode(arr[0]); // 把数组的第一个位置定义为头结点
        ListNode other = head; // 一个指针，此时指向头结点
        for(int i=1;i<arr.length;i++){ //头结点已经定义，从1开始
            ListNode temp = new ListNode(arr[i]);
            other.next = temp;
            other = other.next;

        }//在此处打印结点容易导致head的变化
        return head;
    }

    public static void printNode(ListNode node){
        while(node!=null){
            System.out.print(node.val+" ");
            node = node.next;
        }
    }
    public static void main(String[] args){
        int[] arr = new int[]{1,2,3,4,5,6};
        ListNode node = arrayToNode(arr);
        printNode(node);
        nodeTolist(node);

    }

}
